import { validateCustomPositiveInt, validateCustomADecimal, validateCustomTwoDecimal } from '@/utils/validate'
import { isNull } from '@/utils'

export default {
  data() {
    // 活动时间
    const validateDate = (rule, value, callback) => {
      if (isNull(value)) {
        callback(new Error('请输入活动时间'))
      } else {
        callback()
      }
    }

    //  有效日期
    const validateRuleDataDate = (rule, value, callback) => {
      const startDateArr = []
      const endDateArr = []
      value.some(v => {
        if (!v.date || v.date.length !== 2) {
          callback(new Error('请输入日期区间'))
          return true
        } else if (this.form.date && this.form.date.length === 2 && (v.date[0] < this.form.date[0] || v.date[1] > this.form.date[1])) {
          callback(new Error('日期区间不在活动范围内'))
          return true
        }
        if (value.length === 1) {
          callback()
          return true
        } else {
          startDateArr.push(v.date[0])
          endDateArr.push(v.date[1])
        }
      })
      // 排序
      const startDateSortArr = startDateArr.sort()
      const endDateSortArr = endDateArr.sort()
      // 判断交叉重复
      let flag = false
      for (var k = 1; k < startDateSortArr.length; k++) {
        if (startDateSortArr[k] <= endDateSortArr[k - 1]) {
          flag = true
        }
      }
      if (flag) {
        callback(new Error('日期区间存在交叉重叠'))
      } else {
        callback()
      }
    }
    //  有效时间段
    const validateRuleDataTime = (rule, value, callback) => {
      const startTimeArr = []
      const endTimeArr = []
      value.some(v => {
        if (!v.time || v.time.length !== 2) {
          callback(new Error('请输入时间区间'))
          return true
        } else if (value.length === 1) {
          callback()
          return true
        } else {
          startTimeArr.push(v.time[0])
          endTimeArr.push(v.time[1])
        }
      })
      // 排序
      const startTimeSortArr = startTimeArr.sort()
      const endTimeSortArr = endTimeArr.sort()
      // 判断交叉重复
      let flag = false
      for (var k = 1; k < startTimeSortArr.length; k++) {
        if (startTimeSortArr[k] <= endTimeSortArr[k - 1]) {
          flag = true
        }
      }
      if (flag) {
        callback(new Error('时间区间存在交叉重叠'))
      } else {
        callback()
      }
    }
    //  参与对象
    const validateMemberCategory = (rule, value, callback) => {
      if (this.form.participant === 3 && value.length === 0) {
        callback(new Error('请至少设置一种参与对象'))
      } else {
        callback()
      }
    }

    //  总限制
    const validateMatchPrecision = (rule, value, callback) => {
      if (isNull(value)) {
        callback(new Error('请输入'))
      } else if (!validateCustomPositiveInt(value, 2)) {
        callback(new Error('请输入正整数'))
      } else {
        callback()
      }
    }

    //  规则消费金额
    const validateAward = (rule, value, callback) => {
      if (value.length === 0) {
        callback(new Error('请至少设置一种规则'))
      } else {
        const amountArr = []
        this.form.award.forEach((v) => {
          if (v.amount && validateCustomTwoDecimal(v.amount)) {
            amountArr.push(this.$math.mul(v.amount, 100, 0))
          }
        })
        const oldLen = amountArr.length
        const newLen = [...new Set(amountArr)].length
        if (oldLen !== newLen) {
          callback(new Error('消费金额规则重复'))
        }

        if (this.form.activityType === 4) {
          if (!this.form.award[0].couponData.length) {
            callback('请至少选择一种')
          } else if (value.length > 10) {
            callback('卡券种类不超过10种')
          } else {
            let maxAmount = 0
            let maxWxBusiAmount = 0
            this.form.award[0].couponData.forEach(v => {
              if (validateCustomPositiveInt(v.num, 2)) {
                maxAmount += v.num
                if (['cash_wx_busi', 'discount_wx_busi'].includes(v.couponType)) {
                  maxWxBusiAmount += v.num
                }
              }
            })
            if (maxWxBusiAmount > 10 || maxWxBusiAmount && maxWxBusiAmount !== maxAmount) {
              callback('因为微信限制，如果你选择了微信商家券则此活动所有卡券必须是微信商家券且券总数量不超过10张')
            } else if (maxAmount > 30) {
              callback('卡券总数量不超过30张')
            } else {
              callback()
            }
          }
        } else {
          callback()
        }
      }
    }

    // 校验 rules
    const validateSingleRules = (rule, value, callback) => {
      if (value.length === 0) {
        callback(new Error('请至少设置一种规则'))
      } else {
        const thresholdArr = []
        this.form.singleRules.forEach((v) => {
          if (v.threshold) {
            thresholdArr.push(v.threshold)
          }
        })
        const oldLen = thresholdArr.length
        const newLen = [...new Set(thresholdArr)].length
        if (oldLen !== newLen) {
          callback(new Error('规则重复'))
        } else {
          callback()
        }
      }
    }

    // 校验单品限制
    const validateSingleRulesThreshold = (rule, value, callback) => {
      console.log(rule, value)
      switch (this.form.activityType) {
        case 5:
          if (this.$isNull(value.threshold)) {
            callback(new Error('请输入金额'))
          } else if (!validateCustomTwoDecimal(value.threshold, 7)) {
            callback(new Error('请输入0.01~9999999.99的数字'))
          } else {
            this.$refs.form.clearValidate([rule.fullField])
            callback()
          }
          break
        case 6:
        case 7:
        case 8:
          if (this.$isNull(value.threshold)) {
            callback(new Error('请输入数量'))
          } else if (!validateCustomPositiveInt(value.threshold, 7)) {
            callback(new Error('请输入正整数'))
          } else {
            callback()
          }
          break
      }
    }

    // 校验单品优惠
    const validateSingleRulesAmount = (rule, value, callback) => {
      console.log(value.amount, value.threshold, value.amount >= value.threshold)
      switch (this.form.activityType) {
        case 5:
          if (this.$isNull(value.amount)) {
            callback(new Error('请输入金额'))
          } else if (!validateCustomTwoDecimal(value.amount, 7)) {
            callback(new Error('请输入0.01~9999999.99的数字'))
          } else if (value.threshold && validateCustomTwoDecimal(value.threshold, 7) && (this.$math.mul(value.amount, 100, 0) >= this.$math.mul(value.threshold, 100, 0))) {
            callback(new Error('立减金额应小于消费金额'))
          } else {
            callback()
          }
          break
        case 6:
          if (this.$isNull(value.amount)) {
            callback(new Error('请输入数量'))
          } else if (!validateCustomPositiveInt(value.amount, 7)) {
            callback(new Error('请输入正整数'))
          } else if (value.threshold && validateCustomPositiveInt(value.threshold, 7) && (this.$math.mul(value.amount, 100, 0) >= this.$math.mul(value.threshold, 100, 0))) {
            callback(new Error('免单数量应小于购买数量'))
          } else {
            callback()
          }
          break
        case 8:
          if (this.$isNull(value.amount)) {
            callback(new Error('请输入金额'))
          } else if (!validateCustomTwoDecimal(value.amount, 7)) {
            callback(new Error('请输入0.01~9999999.99的数字'))
          } else {
            callback()
          }
          break
        case 7:
          if (this.$isNull(value.amount)) {
            callback(new Error('请输入折扣'))
          } else if (!validateCustomADecimal(value.amount, 1)) {
            callback(new Error('请输入0.1~9.9的数字'))
          } else {
            callback()
          }
          break
      }
      this.$refs.form.validateField('singleRules')
    }

    // 单品商品
    const validateSingleGoods = (rule, value, callback) => {
      if (isNull(value)) {
        callback(new Error('请输入商品编码'))
      } else {
        const arr = value
          .trim()
          .replace(/\r\n|\n|\r/g, ',')
          .replace(/,+/g, ',')
          .split(',')
        const len = arr.length
        len > 3000 ? callback(new Error('单次最多支持3000个')) : callback()
      }
    }

    // 赠送优惠券数量
    const validateCouponNum = (rule, value, callback) => {
      if (isNull(value)) {
        callback(new Error('请输入数量'))
      } else if (!validateCustomPositiveInt(value, 2)) {
        callback(new Error('请输入正整数'))
      } else {
        this.$refs.form.validateField(['award'])
        callback()
      }
    }
    // 消费金额
    const validateAmount = (rule, value, callback) => {
      if (isNull(value)) {
        callback(new Error('请输入金额'))
      } else if (!validateCustomTwoDecimal(value)) {
        callback(new Error('请输入0.01~99999.99范围金额（小数位不超过2位）'))
      } else {
        callback()
        this.$refs.form.validateField(['award'])
      }
    }
    // 规则余额
    const validateBalance = (rule, value, callback) => {
      if (isNull(value)) {
        callback(new Error('请输入金额'))
      } else if (!validateCustomTwoDecimal(value)) {
        callback(new Error('请输入0.01~99999.99范围金额（小数位不超过2位）'))
      } else {
        callback()
      }
    }
    //  用户天限制
    const validateFrequencyDay = (rule, value, callback) => {
      if (!this.form.frequencyDayCheckedExtra) {
        callback()
      } else if (isNull(value)) {
        callback(new Error('请输入次数'))
      } else if (!validateCustomPositiveInt(value, 8)) {
        callback(new Error('请输入正整数'))
      } else {
        callback()
        this.$refs.form.validateField(['frequencyWeek', 'frequencyMonth', 'frequencyAll'])
      }
    }
    //  用户周限制
    const validateFrequencyWeek = (rule, value, callback) => {
      if (!this.form.frequencyWeekCheckedExtra) {
        callback()
      } else if (isNull(value)) {
        callback(new Error('请输入次数'))
      } else if (!validateCustomPositiveInt(value, 8)) {
        callback(new Error('请输入正整数'))
      } else if (this.form.frequencyDayCheckedExtra && this.form.frequencyDay && validateCustomPositiveInt(this.form.frequencyDay, 8) && +this.form.frequencyDay > +value) {
        callback(new Error('周限制要大于等于日限制'))
      } else {
        callback()
        this.$refs.form.validateField(['frequencyMonth', 'frequencyAll'])
      }
    }
    //  用户月限制
    const validateFrequencyMonth = (rule, value, callback) => {
      if (!this.form.frequencyMonthCheckedExtra) {
        callback()
      } else if (isNull(value)) {
        callback(new Error('请输入次数'))
      } else if (!validateCustomPositiveInt(value, 8)) {
        callback(new Error('请输入正整数'))
      } else if (this.form.frequencyWeekCheckedExtra && this.form.frequencyWeek && validateCustomPositiveInt(this.form.frequencyWeek, 8) && +this.form.frequencyWeek > +value) {
        callback(new Error('月限制要大于等于周限制'))
      } else if (this.form.frequencyDayCheckedExtra && this.form.frequencyDay && validateCustomPositiveInt(this.form.frequencyDay, 8) && +this.form.frequencyDay > +value) {
        callback(new Error('月限制要大于等于日限制'))
      } else {
        callback()
        this.$refs.form.validateField(['frequencyAll'])
      }
    }
    //  用户总限制
    const validateFrequencyAll = (rule, value, callback) => {
      if (!this.form.frequencyAllCheckedExtra) {
        callback()
      } else if (isNull(value)) {
        callback(new Error('请输入次数'))
      } else if (!validateCustomPositiveInt(value, 8)) {
        callback(new Error('请输入正整数'))
      }
      if (this.form.frequencyMonthCheckedExtra && this.form.frequencyMonth && validateCustomPositiveInt(this.form.frequencyMonth, 8) && +this.form.frequencyMonth > +value) {
        callback(new Error('总限制要大于等于月限制'))
      } else if (this.form.frequencyWeekCheckedExtra && this.form.frequencyWeek && validateCustomPositiveInt(this.form.frequencyWeek, 8) && +this.form.frequencyWeek > +value) {
        callback(new Error('总限制要大于等于周限制'))
      } else if (this.form.frequencyDayCheckedExtra && this.form.frequencyDay && validateCustomPositiveInt(this.form.frequencyDay, 8) && +this.form.frequencyDay > +value) {
        callback(new Error('总限制要大于等于日限制'))
      } else {
        callback()
      }
    }
    //  总限制
    const validateBudget = (rule, value, callback) => {
      if (!this.form.budgetCheckedExtra) {
        callback()
      } else if (isNull(value)) {
        callback(new Error('请输入次数'))
      } else if (!validateCustomPositiveInt(value, 8)) {
        callback(new Error('请输入正整数'))
      } else {
        callback()
      }
    }
    //  天限制
    const validatePerdayBudget = (rule, value, callback) => {
      if (!this.form.perdayBudgetCheckedExtra) {
        callback()
      } else if (isNull(value)) {
        callback(new Error('请输入次数'))
      } else if (!validateCustomPositiveInt(value, 8)) {
        callback(new Error('请输入正整数'))
      } else {
        callback()
      }
    }
    //  可使用门店
    const validateShop = (rule, value, callback) => {
      if (this.form.shopRadioExtra === 2 && value.length === 0) {
        callback(new Error('请至少设置一家可使用门店'))
      } else {
        callback()
      }
    }
    //  参与交易类型
    const validateBizType = (rule, value, callback) => {
      if (this.form.bizTypeRadioExtra === 2 && value.length === 0) {
        callback(new Error('请至少设置一个参与的交易类型'))
      } else {
        callback()
      }
    }
    //  参与支付方式
    const validatePayType = (rule, value, callback) => {
      if (this.form.payTypeRadioExtra === 2 && value.length === 0) {
        callback(new Error('请至少设置一种支付方式'))
      } else {
        callback()
      }
    }
    //  参与付款方式
    const validateBankCode = (rule, value, callback) => {
      if ((this.form.limitPay === 2 || this.form.limitPay === 3) && value.length === 0) {
        callback(new Error('请选择付款方式'))
      } else {
        callback()
      }
    }

    return {
      //  表单校验字段相关
      rules: {
        theme: [
          {
            required: true,
            message: '请输入活动主题',
            trigger: ['blur', 'change']
          }
        ],
        image: [
          {
            required: true,
            message: '请上传图片',
            trigger: ['blur', 'change']
          }
        ],
        date: [
          {
            required: true,
            validator: validateDate,
            trigger: ['blur', 'change']
          }
        ],
        ruleDataWeek: [
          {
            type: 'array',
            required: true,
            message: '请选择每周使用日期',
            trigger: ['blur', 'change']
          }
        ],
        ruleDataDate: [
          {
            required: true,
            validator: validateRuleDataDate,
            trigger: ['blur', 'change']
          }
        ],
        ruleDataTime: [
          {
            required: true,
            validator: validateRuleDataTime,
            trigger: ['blur', 'change']
          }
        ],
        memberCategory: [
          {
            type: 'array',
            required: true,
            validator: validateMemberCategory,
            trigger: ['blur', 'change']
          }
        ],
        specificBank: [
          {
            required: true,
            message: '请输入银行名称',
            trigger: ['blur', 'change']
          }
        ],
        phoneListKey: [
          {
            required: true,
            message: '请上传文件',
            trigger: ['blur', 'change']
          }
        ],
        matchPrecision1: [
          {
            required: true,
            validator: validateMatchPrecision,
            trigger: ['blur', 'change']
          }
        ],
        matchPrecision2: [
          {
            required: true,
            validator: validateMatchPrecision,
            trigger: ['blur', 'change']
          }
        ],
        award: [
          {
            required: true,
            validator: validateAward,
            trigger: ['blur', 'change']
          }
        ],
        singleRules: [
          {
            required: true,
            validator: validateSingleRules,
            trigger: ['blur', 'change']
          }
        ],
        singleRulesThreshold: [
          {
            required: true,
            validator: validateSingleRulesThreshold,
            trigger: ['blur', 'change']
          }
        ],
        singleRulesAmount: [
          {
            required: true,
            validator: validateSingleRulesAmount,
            trigger: ['blur', 'change']
          }
        ],
        singleGoods: [
          {
            required: true,
            validator: validateSingleGoods,
            trigger: ['blur', 'change']
          }
        ],
        couponNum: [
          {
            // type: 'array',
            required: true,
            // message: '请至少设置一种规则',
            validator: validateCouponNum,
            trigger: ['blur', 'change']
          }
        ],
        amount: [
          {
            required: true,
            validator: validateAmount,
            trigger: ['blur', 'change']
          }
        ],
        balance: [
          {
            required: true,
            validator: validateBalance,
            trigger: ['blur', 'change']
          }
        ],
        wxMchId: [
          {
            required: true,
            message: '请输入微信商户号',
            trigger: ['blur', 'change']
          }
        ],
        appId: [
          {
            required: true,
            message: '请输入微信APPID',
            trigger: ['blur', 'change']
          }
        ],
        sender: [
          {
            required: true,
            message: '请输入发送者名称',
            trigger: ['blur', 'change']
          }
        ],
        blessing: [
          {
            required: true,
            message: '请输入祝福语',
            trigger: ['blur', 'change']
          }
        ],
        frequencyDay: [
          {
            required: true,
            validator: validateFrequencyDay,
            trigger: ['blur', 'change']
          }
        ],
        frequencyWeek: [
          {
            required: true,
            validator: validateFrequencyWeek,
            trigger: ['blur', 'change']
          }
        ],
        frequencyMonth: [
          {
            required: true,
            validator: validateFrequencyMonth,
            trigger: ['blur', 'change']
          }
        ],
        frequencyAll: [
          {
            required: true,
            validator: validateFrequencyAll,
            trigger: ['blur', 'change']
          }
        ],
        budget: [
          {
            required: true,
            validator: validateBudget,
            trigger: ['blur', 'change']
          }
        ],
        perdayBudget: [
          {
            required: true,
            validator: validatePerdayBudget,
            trigger: ['blur', 'change']
          }
        ],
        shop: [
          {
            type: 'array',
            required: true,
            validator: validateShop,
            trigger: ['blur', 'change']
          }
        ],
        bizType: [
          {
            type: 'array',
            required: true,
            validator: validateBizType,
            trigger: ['blur', 'change']
          }
        ],
        payType: [
          {
            type: 'array',
            required: true,
            validator: validatePayType,
            trigger: ['blur', 'change']
          }
        ],
        bankCode: [
          {
            type: 'array',
            required: true,
            validator: validateBankCode,
            trigger: ['blur', 'change']
          }
        ]
      }
    }
  },
  watch: {
    'form.calculateTypeExtra'(val) {
      // 多个切换单选多选 重置
      if (this.form.award.length >= 2 && val === 2) {
        this.$confirm(
          '若选择消费每满赠礼只能设置一种规则，其它规则都会被删除，是否继续?',
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            center: true,
            roundButton: true
          }
        )
          .then(() => {
            this.form.award = [this.form.award[0]]
          })
          .catch(() => {
            this.form.calculateTypeExtra = 1
          })
      }
    },
    form: {
      handler: function(val) {
        this.$nextTick(() => {
          //  参与对象
          if (val.participant === 1 || val.participant === 2) {
            this.$refs.form.clearValidate(['memberCategory'])
          } else if (val.participant === 3 && val.memberCategory.length !== 0) {
            this.$refs.form.clearValidate(['memberCategory'])
          } else if (val.participant === 4 || val.participant === 5) {
            this.$refs.form.clearValidate(['specificBank', 'phoneListKey'])
          }
          // 门店
          if (val.shopRadioExtra === 1) {
            this.$refs.form.clearValidate(['shop'])
          } else if (val.shopRadioExtra === 2 && val.shop.length !== 0) {
            this.$refs.form.clearValidate(['shop'])
          }
          // 交易类型
          if (val.bizTypeRadioExtra === 1) {
            this.$refs.form.clearValidate(['bizType'])
          } else if (val.bizTypeRadioExtra === 2 && val.bizType.length !== 0) {
            this.$refs.form.clearValidate(['bizType'])
          }
          // 支付方式
          if (val.payTypeRadioExtra === 1) {
            this.$refs.form.clearValidate(['payType'])
          } else if (val.payTypeRadioExtra === 2 && val.payType.length !== 0) {
            this.$refs.form.clearValidate(['payType'])
          }
          // 付款方式
          if (val.limitPay === 1) {
            this.$refs.form.clearValidate(['bankCode'])
          } else if ((val.limitPay === 2 || val.limitPay === 3) && val.limitPay.length !== 0) {
            this.$refs.form.clearValidate(['bankCode'])
          }
        })
      },
      deep: true
    }
  },
  methods: {}

}
